package remote.service;

import client.common.dto.*;
import client.common.result.Result;
import client.common.result.UserListResult;
import client.common.result.UserPageResult;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import remote.common.constant.UrlConstant;
import remote.common.storage.TokenStorage;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 */
public interface UserService {
    /**
     * 登录
     *
     * @param loginReqDTO 登录参数
     * @return 登录结果
     */
    default Result<String> login(LoginReqDTO loginReqDTO) {
        // 向服务器发送登录请求
        String resultBodyStr = HttpUtil.post(UrlConstant.BASE_URL + "/login", JSON.toJSONString(loginReqDTO));
        return JSON.parseObject(resultBodyStr, new TypeReference<Result<String>>() {
        });
    }
    
    /**
     * 获取所有用户列表
     *
     * @param adminPageDTO 分页参数
     * @return 用户列表
     */
    default UserPageResult getUserPage(AdminPageDTO adminPageDTO) {
        HashMap<String, Object> requestParam = new HashMap<>();
        requestParam.put("current", adminPageDTO.getCurrent());
        requestParam.put("size", adminPageDTO.getSize());
        String resultStr = HttpRequest.get(UrlConstant.BASE_URL + "/user/page/getUserList")
                .header("Authorization", TokenStorage.getToken())
                .form(requestParam)
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, UserPageResult.class);
    }
    
    /**
     * 超管修改用户接口
     *
     * @return Result
     */
    default Result updateUser(AdminUpdateDTO requestParam) {
        String resultStr = HttpRequest.put(UrlConstant.BASE_URL + "/user/updateUser")
                .header("Authorization", TokenStorage.getToken())
                .body(JSON.toJSONString(requestParam))
                .execute()
                .body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
    }
    
    /**
     * 超管删除用户接口 （逻辑删除 将DelFlag置为1）
     *
     * @param userId 用户id
     * @return Result
     */
    default Result deleteUser(String userId) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("id", userId);
        String resultStr = HttpRequest.delete(UrlConstant.BASE_URL + "/user/deleteUser")
                .header("Authorization", TokenStorage.getToken())
                .form(requestParam)
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
        
    }
    
    /**
     * 超管根据真实姓名 模糊查询用户接口
     *
     * @param realName 真实姓名
     * @return 用户列表
     */
    default UserListResult fuzzyQueryUserByRealName(String realName) {
        HashMap<String, Object> requestMap = new HashMap<>();
        requestMap.put("searchText", realName);
        String resultStr = HttpRequest.get(UrlConstant.BASE_URL + "/user/fuzzyQueryUser")
                .header("Authorization", TokenStorage.getToken())
                .form(requestMap)
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, UserListResult.class);
    }
    
    /**
     * 超管添加用户接口
     *
     * @param requestParam 用户信息
     * @return Result
     */
    default Result addUser(AdminRegisterReqDTO requestParam) {
        String resultStr = HttpRequest.post(UrlConstant.BASE_URL + "/user/addUser")
                .header("Authorization", TokenStorage.getToken())
                .body(JSON.toJSONString(requestParam))
                .execute()
                .body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
    }
    
    /**
     * 修改用户角色
     */
    default Result<String> updateUserRole(Long userId, Integer roleId) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("userId", userId);
        requestParam.put("roleId", roleId);
        String resultStr = HttpRequest.put(UrlConstant.BASE_URL + "/user/updateUserRole")
                .header("Authorization", TokenStorage.getToken())
                .form(requestParam)
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
    }
    
    /**
     * bug反馈
     */
    default Result bugReport(BugReportDto bugReportDto) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        BugReportValueDto bugReportValueDto = BugReportValueDto.builder()
                .contactDetails(bugReportDto.getContactDetails())
                .description(bugReportDto.getDescription())
                .time(sf.format(bugReportDto.getTime()) + ":00").build();
        String resultStr = HttpRequest.get(UrlConstant.BASE_URL + "/user/bugReport")
                .header("Authorization", TokenStorage.getToken())
                .body(JSON.toJSONString(bugReportValueDto))
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
    }
    
    /**
     * 优化建议反馈
     */
    default Result uploadSuggestion(String suggestion, String contactDetails) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("suggestion", suggestion);
        requestParam.put("contactDetails", contactDetails);
        String resultStr = HttpRequest.get(UrlConstant.BASE_URL + "/user/uploadSuggestion")
                .header("Authorization", TokenStorage.getToken())
                .form(requestParam)
                .execute().body();
        System.out.println(resultStr);
        return JSON.parseObject(resultStr, Result.class);
    }
    /**
     * excel批量导入用户
     */
    default Result<String> importUserByExcel(File file) {
        try {
            URL url = new URL(UrlConstant.BASE_URL + "/user/importUserByExcel");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            connection.setRequestProperty("Authorization",  TokenStorage.getToken()); // 添加 token

            try (OutputStream os = connection.getOutputStream();
                 FileInputStream fis = new FileInputStream(file)) {

                os.write(("--" + boundary + "\r\n" +
                        "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n" +
                        "Content-Type: application/vnd.ms-excel\r\n\r\n").getBytes());

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.write(("\r\n--" + boundary + "--\r\n").getBytes());
                os.flush();
            }
            Integer responseCode = connection.getResponseCode();
            System.out.println(responseCode);

            return responseCode==200?Result.success("上传成功"):Result.fail("上传失败");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail("上传失败");
    }
}
